package top.csmcool.musicapi.client;


import cn.hutool.json.JSONObject;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import top.csmcool.musicapi.enums.PlatformEnum;
import top.csmcool.musicapi.resource.MusicUrlResource;
import top.csmcool.musicapi.util.MusicRequestUtil;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * @Description
 * @Author shizhe
 * @Date 2025/02/08
 */

@Getter
public abstract class CommonClient {

    @Autowired
    private MusicUrlResource musicUrlResource;

    @Autowired
    private MusicRequestUtil musicRequestUtil;
    private final String METHOD_NAME = "method";

    public String getUrl(JSONObject parameter) {
        String URL_ARG_NAME = "url";
        String method = parameter.getStr(METHOD_NAME);
        String url = parameter.getStr(URL_ARG_NAME);
        if(url == null) {
            url = musicUrlResource.getResourceUrl(method, getPlatform());
        }
        if (url == null) {
            url = convertToPath(method);
        }
        parameter.remove(URL_ARG_NAME);
        parameter.remove(METHOD_NAME);
        return url;
    }

    protected static String convertToPath(String input) {
        if (input == null || input.isEmpty()) {
            return "/";
        }
        // 使用正则表达式将驼峰命名转换为小写并用斜杠分隔
        String path = input.replaceAll("([A-Z])", "/$1").toLowerCase();
        // 确保路径以斜杠开头
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        return path;
    }

    public abstract PlatformEnum getPlatform();

    protected static String generateGetRequestUrl(JSONObject params) {
        if (params == null || params.isEmpty()) {
            return ""; // 如果没有参数，直接返回基础URL
        }

        // 构建查询参数字符串
        StringBuilder queryBuilder = new StringBuilder();
        Set<Map.Entry<String, Object>> entries = params.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            if (!queryBuilder.isEmpty()) {
                queryBuilder.append("&"); // 添加分隔符
            }
            try {
                // 对键和值进行URL编码
                queryBuilder.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 拼接完整的URL
        return "?" + queryBuilder.toString() + "&";
    }

    public JSONObject requestResource(JSONObject jsonObject) {
        return musicRequestUtil.sendRequestAutowiredJson(jsonObject, getUrl(jsonObject));
    }
}
